import React from 'react';
import { createBehavior, createResource } from '@inbiz/core';
import TableDesigner from '../../preview/wap/index';
import { DnFC } from '@inbiz/react';
import {
  createBaseSchema,
  createComponentStyleSchema,
  createControllerSchema,
  createDecoratorStyleSchema,
  createInbizSchema,
  createSoureSchema,
  getDefalutDecoratorProps,
} from '@inbiz/setters';
import * as Schema from '../web/schema';
import * as Locale from '../locale';
import { H5TableStyle } from '../web/schema';
import { Field } from '@formily/core';

const Table: DnFC<React.ComponentProps<typeof TableDesigner>> = TableDesigner;

const createSchema = (name: string) => {
  return createInbizSchema({
    attribute: {
      ...createBaseSchema(Schema[name], undefined, true),
    } as any,
    style: {
      ...createComponentStyleSchema(H5TableStyle),
      ...createDecoratorStyleSchema(),
    },
    senior: {
      ...createSoureSchema({
        isApi: true,
        types: ['search'],
        fieldChange: (form, value: any) => {
          if (!value?.isChangeModel) {
            return;
          }
          const formItems = {
            pageSize: 10,
            searchFiled: value.queryField?.[0]?.FieldName,
            selected: 'default',
          };
          const queryFields = value.queryField
            ?.filter((field: any) => !field.IsMany)
            ?.map((item: any) => {
              return {
                value: item.AnotherName
                  ? item.AnotherName
                  : item.Master
                    ? item.FieldName.split('$')[1]
                    : item.FieldName,
                label: item.AnotherName
                  ? item.AnotherName
                  : item.Master
                    ? item.FieldName.split('$')[1]
                    : item.FieldName,
                ModelKey: item.ModelKey,
                Master: item.Master,
                origin_FieldName: item.FieldName,
                sourcetype: 'modal',
                columnName: item.ColName
              };
            });
          const attrs = queryFields.map((item: any) => {
            return {
              propName: item.value,
              visible: '1',
              width: 100,
              columnName: item.columnName
            };
          });
          const field = form.query(/columnConfig$/).take() as Field;

          if (field.value.tableValues.attrs?.length) {
            // 有值的时候过滤掉不存在的查询字段
            let newAttrs: any[] = [];
            attrs.map((item: any) => {
              field.value.tableValues.attrs.map((fieldItem: any) => {
                if (item.propName == fieldItem.propName) {
                  newAttrs.push({
                    propName: item.propName,
                    visible: '1',
                    width: 100,
                  });
                }
              });
            });
            field.value = {
              ...field.value,
              queryFields,
              tableValues: {
                actions: [],
                attrs: newAttrs,
              },
            };
          } else {
            // 没有的时候设置值
            field.value = {
              formItems,
              queryFields,
              tableValues: {
                actions: [],
                attrs,
              },
            };
          }
        },
      })
    },
    controller: createControllerSchema({
      events: [
      {
        name: "onOpen",
        label: "页面打开事件",
      },
      {
        name: "onClick",
        label: "点击事件",
      },
      {
        name: 'onRead',
        label: '查看按钮事件'
      },
      {
        name: 'onEdit',
        label: '编辑按钮事件'
      },
      {
        name: 'onDelete',
        label: '删除按钮事件'
      },
      {
        name: 'onCustom',
        label: '自定义按钮事件'
      },
      {
        name: "onLoad",
        label: "初始化事件",
      },
      {
        name: "onAdd",
        label: "数据添加事件",
      },
      {
        name: "onEdit",
        label: "数据修改事件",
      },
      {
        name: "onDelete",
        label: "数据删除事件",
      },
      {
        name: "onSuccess",
        label: "数据请求成功事件",
      },
      {
        name: "onError",
        label: "数据请求失败事件",
      },
      {
        name: "onParamFormat",
        label: "格式化参数",
        isConfigEvent: true,
      },
      {
        name: "onRequest",
        label: "自定义请求",
        isConfigEvent: true,
      },
      {
        name: "onData",
        label: "格式化数据",
        isConfigEvent: true,
      },
      {
        name: 'onOpenChildUrl',
        label: "打开子页面时执行",
        isConfigEvent: true,
      },
      {
        name: "onBeforeOperationAsync",
        label: "新增/编辑/删除前执行",
        isConfigEvent: true,
      }]
    })
  });
};

export const defaultTableProps = {
  autoLoad: true,
  search: true,
  searchPlacehoder: 'Table.pleaseEnterTheSearchContent',
  columnConfig: {
    formItems: {
      pageSize: 10,
    },
    tableValues: {
      actions: [],
      // actions: Actions.reduce((data: any[], action) => {
      //   if (
      //     ![ActionEnum.add, ActionEnum.view, ActionEnum.edit].includes(action.value as ActionEnum)
      //   ) {
      //     return data;
      //   }
      //   data.push({
      //     id: uuid(5, 5),
      //     actionType: action.value,
      //     actionName: action.label,
      //     position:
      //       action.value === ActionEnum.add ? ActionPosition.tableHeader : ActionPosition.inline,
      //     openMode: 'modal',
      //     windowName: action.label,
      //   });
      //   return data;
      // }, []),
    },
  },
};

Table.Behavior = createBehavior({
  name: 'Table',
  extends: ['Field'],
  selector: (node) => node.props?.['x-component'] === 'Table',
  designerProps: {
    droppable: true,
    propsSchema: createSchema('Table'),
  },
  designerLocales: Locale.Table,
});

Table.Resource = createResource({
  icon: 'Table',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'void',
        title: {
          value: 'Table.title',
          status: true,
        },
        'x-decorator': 'FormItemVertical',
        'x-decorator-props': {
          style: {
            height: '100%',
            backgroundColor: 'rgb(245,245,245)',
          },
        },
        'x-component': 'Table',
        'x-component-props': defaultTableProps,
      },
    },
  ],
});

export default Table;
